package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WebServerOrder;
import com.ruoyi.system.domain.WebServerUser;
import com.ruoyi.system.domain.WebUserCardTime;
import com.ruoyi.system.mapper.WebServerOrderMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.WebServerOrderSaveVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务预约订单Service业务层处理
 * 
 * @author wsliupan@126.com
 * @date 2021-06-23
 */
@Service
public class WebServerOrderServiceImpl extends ServiceImpl<WebServerOrderMapper, WebServerOrder> implements IWebServerOrderService
{
    @Autowired
    private WebServerOrderMapper webServerOrderMapper;
    @Autowired
    private IWebUserCardTimeService webUserCardTimeService;
    @Autowired
    private IWebServerOrderFlowService iWebServerOrderFlowService;
    @Autowired
    private IWebServerUserService iWebServerUserService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private IWebServerOrderService webServerOrderService;
    /**
     * 查询服务预约订单
     * 
     * @param id 服务预约订单ID
     * @return 服务预约订单
     */
    @Override
    public WebServerOrder selectWebServerOrderById(Long id)
    {
        return webServerOrderMapper.selectWebServerOrderById(id);
    }

    /**
     * 查询服务预约订单列表
     * 
     * @param webServerOrder 服务预约订单
     * @return 服务预约订单
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<WebServerOrder> selectWebServerOrderList(WebServerOrder webServerOrder)
    {
        return webServerOrderMapper.selectWebServerOrderList(webServerOrder);
    }

    /**
     * 新增服务预约订单
     * 
     * @param webServerOrder 服务预约订单
     * @return 结果
     */
    @Override
    public int insertWebServerOrder(WebServerOrder webServerOrder)
    {
        webServerOrder.setCreateTime(DateUtils.getNowDate());
        return webServerOrderMapper.insertWebServerOrder(webServerOrder);
    }

    /**
     * 修改服务预约订单
     * 
     * @param webServerOrder 服务预约订单
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updateWebServerOrder(WebServerOrder webServerOrder)
    {
        //webServerOrder.setUpdateTime(DateUtils.getNowDate());
        //return webServerOrderMapper.updateWebServerOrder(webServerOrder);
        if(webServerOrder.getId() == null){
            webServerOrder.setOrderNo(StringUtils.seqOrderNum("FA",10));

            //如果是今天之前的，就不要验证
            Date preDate = null;
            try {
                String preDay = webServerOrder.getPreDay().replace("/","-");
                preDate = DateUtils.parseDate(preDay, DateUtils.YYYY_MM_DD);
            }catch (Exception e){}
//                preDay = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, preDate);
                if(preDate.after(DateUtils.getNowDate())){
                    List<String> times = iSysDeptService.selectServerUserTime(webServerOrder.getPreDay(),webServerOrder.getDeptId(),Integer.valueOf(webServerOrder.getServerUserId()) , true);
                    if(CollectionUtils.isEmpty(times)){
                        throw new BusinessException("该技师此时间段已被预约");
                    }

                    int count = webServerOrderService.count(new QueryWrapper<WebServerOrder>()
                            .eq("pre_day",webServerOrder.getPreDay())
                            .eq("pre_time",webServerOrder.getPreTime())
                            .eq("server_user_id",webServerOrder.getServerUserId())
                            .ne("status",3)
                    );
                    if(count > 0){
                        throw new BusinessException("此技师的该时间段已被预约");
                    }
                }

        }

//        int count = this.count(new QueryWrapper<WebServerOrder>()
//                .eq("pre_day",webServerOrder.getPreDay())
//                .eq("pre_time",webServerOrder.getPreTime())
//                .eq("server_user_id",webServerOrder.getServerUserId())
//                .ne("status",3)
//        );
//        if(count > 0){
//            throw new BusinessException("此技师的该时间段已被预约");
//        }

        //已完成
        if(webServerOrder.getStatus() == 2){
            if(webServerOrder.getId() != null){
                WebServerOrder serverOrderData = this.getById(webServerOrder.getId());
                if(serverOrderData != null && serverOrderData.getCutDown()==0){
                    //处理次卡
                    List<WebUserCardTime> webUserCardTimes = webUserCardTimeService.list(new QueryWrapper<WebUserCardTime>()
                            .eq("user_id",webServerOrder.getUserId())
                            .eq("recycle_type_id",webServerOrder.getRecycleTypeId())
                            .eq("status","Y")
                            .gt("times",0)
                            .orderByAsc("create_time"));
                    if(CollectionUtils.isNotEmpty(webUserCardTimes)){
                        WebUserCardTime webUserCardTime = webUserCardTimes.get(0);
                        webUserCardTimeService.consumption(webUserCardTime , webServerOrder.getPreDay()+" "+webServerOrder.getPreTime() ,webServerOrder.getId());

//                        if(webServerOrder.getRecycleTypeId().longValue() != serverOrderData.getRecycleTypeId().longValue()){
//                            WebUserCardTime oldCard = webUserCardTimeService.getById(webUserCardTime.getRecycleTypeId());
//                            webUserCardTimeService.update(new UpdateWrapper<WebUserCardTime>().eq("id",webUserCardTimeService).set("times",oldCard.getTimes()+1));
//                        }

                        webServerOrder.setCutDown(1); //标识已经减过次卡
                    }
                }
            }



        }
        return this.saveOrUpdate(webServerOrder);
    }

    /**
     * 删除服务预约订单对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public boolean deleteWebServerOrderByIds(String ids)
    {
        //return webServerOrderMapper.deleteWebServerOrderByIds(Convert.toStrArray(ids));
        return this.removeByIds(Arrays.asList(Convert.toStrArray(ids)));
    }

    /**
     * 删除服务预约订单信息
     * 
     * @param id 服务预约订单ID
     * @return 结果
     */
    @Override
    public boolean deleteWebServerOrderById(Long id)
    {
        //return webServerOrderMapper.deleteWebServerOrderById(id);
        return this.removeById(id);
    }

    /**
     * 确认订单
     * @param orderSaveVO
     * @return
     */
    @Transactional
    public boolean confirmSave(WebServerOrderSaveVO orderSaveVO){
        orderSaveVO.setWebServerOrderFlow(orderSaveVO.getWebServerOrderFlow().stream().filter(vo -> vo.getFlowId() != null).collect(Collectors.toList()));
        orderSaveVO.getWebServerOrderFlow().stream().filter(vo -> vo.getFlowId() != null).forEach(flow ->{
            flow.setOrderId(orderSaveVO.getOrderId());
            WebServerUser webServerUser= iWebServerUserService.getById(flow.getServerUserId());
            flow.setServerUserName(webServerUser.getRealname());
        });
        iWebServerOrderFlowService.deleteWebServerOrderFlowByOrderId(Long.valueOf(orderSaveVO.getOrderId()));
        iWebServerOrderFlowService.saveBatch(orderSaveVO.getWebServerOrderFlow());

        WebServerOrder serverOrder = this.getById(orderSaveVO.getOrderId());
        serverOrder.setStatus(2);
        serverOrder.setRecycleType(orderSaveVO.getRecycleType());
        serverOrder.setRecycleTypeId(Long.valueOf(orderSaveVO.getRecycleTypeId()));
        serverOrder.setComment(orderSaveVO.getComment());
        if(StringUtils.isEmpty(serverOrder.getServerUserId())){
            serverOrder.setServerUserId(String.valueOf(orderSaveVO.getWebServerOrderFlow().get(0).getServerUserId()));
        }
        this.saveOrUpdate(serverOrder);
        //用户次卡抵扣
        if(orderSaveVO.getRecycleTypeId() != null && orderSaveVO.getRecycleTypeId().intValue() == serverOrder.getRecycleTypeId().intValue()){
            List<WebUserCardTime> cardTimes = webUserCardTimeService.list(new QueryWrapper<WebUserCardTime>()
                    .eq("user_id",serverOrder.getUserId())
                    .eq("recycle_type_id",serverOrder.getRecycleTypeId())
                    .eq("status","Y")
                    .gt("times",0)
                    .orderByAsc("create_time"));
            if(CollectionUtils.isNotEmpty(cardTimes)){
                WebUserCardTime cardTime = cardTimes.get(0);
                webUserCardTimeService.consumption(cardTime,serverOrder.getPreDay()+" "+serverOrder.getPreTime(),serverOrder.getId());
            }
        }
        return  true;
    }

    /**
     * 统计
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<Map> selectIndexData(WebServerOrder webServerOrder){
        return webServerOrderMapper.selectIndexData(webServerOrder);
    }


    /**
     * 统计
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<Map> selectIndexDataOfPie(WebServerOrder webServerOrder){
        return webServerOrderMapper.selectIndexDataOfPie(webServerOrder);
    }

    @Override
    @DataScope(deptAlias = "t1")
    public List<Map> selectIndexDataOfList(WebServerOrder webServerOrder){
        return webServerOrderMapper.selectIndexDataOfList(webServerOrder);
    }

}
